import { ref, computed, reactive, watch } from 'vue'
import { defineStore } from 'pinia'
import { get, set } from "@/data/persistent/localStorage";
import { ROULETTE_DATA, ROULETTE_DATA_LIST, SETTING_PREFIX } from "@/data/constants/Constants";
import { ElNotification } from "element-plus";

export const useRouletteDataStore = defineStore('rouletteData', () => {

    const rouletteDataList = reactive(get(ROULETTE_DATA_LIST) || [])
    const rouletteData = ref(get(ROULETTE_DATA) || rouletteDataList[0] || null)

    function getRouletteDataList(){
        return rouletteDataList
    }

    function addRouletteData(name:string):string|null{
        let reg = new RegExp('[\\\\/:*?"<>|]')
        if (reg.test(name)) {
            ElNotification({
                title: 'Error',
                message: '文件名不能包含下列任何字符:\n\\/:*?"<>|',
                type: 'error',
                duration: 0,
            })
            return null
        }
        if (rouletteDataList.indexOf(name) < 0 && name !== '') {
            rouletteDataList.push(name)
            return name
        }
        return null
    }

    function delRouletteData(name:string){
        const index = rouletteDataList.indexOf(name)
        rouletteDataList.splice(index, 1)
        rouletteData.value = rouletteDataList[0]
    }

    watch(
        rouletteDataList,
        async (rouletteDataList)=>{
            set(ROULETTE_DATA_LIST, rouletteDataList)
        },
        {deep:true}
    )

    watch(
        rouletteData,
        async (rouletteData) => {
            set(ROULETTE_DATA, rouletteData)
        }
    )

    return { rouletteData: rouletteData, rouletteDataList: rouletteDataList, getRouletteDataList, addRouletteData, delRouletteData }
})